Online-Academy
Look, Read, Understand, Apply

Loading templates and Passing values to temples - django

We can create separate html page and can render in the view. To render html pages, we create new folder named templates in the web app (let our web app name be aaa) and store HTML files inside the templates folder.

In the views.py file, we import loader from django.template.

from django.template import loader

    def showhtml(request):
        template = loader.get_template('first.html') # first.html is saved in side templates folder
        return HttpResponse(template.render())

In the urls.py folder, add new path like

path('showhtml/',views.showhtml,name='showhtml'),

Here, showhtml function defined inside views.py file loads html file.

Change Settings

To have to specify that new app is created to Django. This is done in the settings.py file of project folder. We will find INSTALLED_APPS list there and add the app name (in our case: aaa).

        INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'aaa'  # our app name is aaa and it is added here. 
]
    

Passing data to templates (html pages)

Different methods can be used to provide data to template pages. Here, we will pass data from view to template. We define function in the views.py, and from the view we pass data to template like following:

def showhtml(request):
  template = loader.get_template('first.html')
  dict = {
      "name":["sabrina","Sheetal","Binod"],
      "age":[58,37,51]
  }
  return HttpResponse(template.render(dict))

Here, dict is dictionary object and it is passed to template through render method.

we access the passed data in the template as follows:

    {%for n in name%}
        
  • {{n}}
  • {%endfor%} {%for n in age%}
  • {{n}}
  • {%endfor%}